package com.rsscollector.util;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;

public class QuartzUtil {
	
	public static Logger logger = Logger.getLogger(QuartzUtil.class.getName());
	
	public static List<Trigger> getTriggersFromJob(Scheduler scheduler, JobDetail jobDetail) throws Exception {
		
		String jobName = jobDetail.getName();
		String jobGroup = jobDetail.getGroup();
		
		List<Trigger> triggerList = new ArrayList<Trigger>();
		String[] groups = scheduler.getTriggerGroupNames();

		for (String group : groups) {
			for (String name : scheduler.getTriggerNames(group)) {
				Trigger trigger = scheduler.getTrigger(name, group);

				if (trigger == null) {
					logger.warn("The trigger " + name + " in group " + group + " was null");
					continue;
				}

				if (trigger.getJobName().equals(jobName) && trigger.getJobGroup().equals(jobGroup)) {
					triggerList.add(trigger);
				}
			}
		}

		return triggerList;
	}

	public static List<JobDetail> getJobs(Scheduler scheduler)
			throws SchedulerException {
		List<JobDetail> jobList = new ArrayList<JobDetail>();

		String[] jobGroups = scheduler.getJobGroupNames();
		ArrayList<String> addedJobs = new ArrayList<String>(jobGroups.length);
		for (String groupName : jobGroups) {
			String[] jobs = scheduler.getJobNames(groupName);
			for (int j = 0; j < jobs.length; j++) {
				String job = jobs[j];
				JobDetail jobDetail = scheduler.getJobDetail(job, groupName);
				String key = job + groupName;
				if (!addedJobs.contains(key)) {
					jobList.add(jobDetail);
					addedJobs.add(key);
				}
			}
		}
		return jobList;
	}

}
